import { VxeUI } from 'vxe-pc-ui';
import { ElLink, ElIcon } from 'element-plus';
import { Download } from '@element-plus/icons-vue';

VxeUI.renderer.add('RaFileDownloadRender', {
  renderDefault(renderOpts, params) {
    const { row, column } = params;
    const { props = {} } = renderOpts;
    const field = column.field;
    const fileData = row[field]; // 获取文件数据（可能是URL或URL数组）

    // 如果数据为空，则不显示任何内容或显示占位符
    if (!fileData) {
      return <span>-</span>;
    }

    // 从URL中提取文件名，如果无法提取则使用默认名称
    const getFileName = (url) => {
      try {
        const urlObj = new URL(url);
        const pathname = urlObj.pathname;
        const fileName = pathname.split('/').pop();
        return fileName || '下载文件';
      } catch (error) {
        return '下载文件';
      }
    };

    // 处理文件下载
    const handleDownload = (fileUrl, fileName) => (e) => {
      e.preventDefault();
      e.stopPropagation();

      // 创建一个临时的a标签来触发下载
      const link = document.createElement('a');
      link.href = fileUrl;
      link.download = fileName;
      link.target = '_blank';

      // 添加到DOM，点击，然后移除
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    };

    // 判断是否为数组
    if (Array.isArray(fileData)) {
      // 处理文件数组，显示前三个
      const filesToShow = fileData.slice(0, 3);
      const remainingCount = fileData.length - 3;

      return (
        <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
          {filesToShow.map((fileUrl, index) => {
            if (!fileUrl) return null;

            const fileName = getFileName(fileUrl);

            return (
              <ElLink
                key={index}
                type="primary"
                underline="never"
                onClick={handleDownload(fileUrl, fileName)}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '4px',
                  cursor: 'pointer',
                  fontSize: '12px',
                }}
                {...props}
              >
                <ElIcon size={12}>
                  <Download />
                </ElIcon>
                <span>{fileName}</span>
              </ElLink>
            );
          })}
          {remainingCount > 0 && (
            <span
              style={{
                fontSize: '11px',
                color: '#909399',
                fontStyle: 'italic',
              }}
            >
              还有 {remainingCount} 个文件...
            </span>
          )}
        </div>
      );
    } else {
      // 处理单个文件（原有逻辑）
      const fileUrl = fileData;
      const fileName = getFileName(fileUrl);

      return (
        <ElLink
          type="primary"
          underline="never"
          onClick={handleDownload(fileUrl, fileName)}
          style={{
            display: 'flex',
            alignItems: 'center',
            gap: '4px',
            cursor: 'pointer',
          }}
          {...props}
        >
          <ElIcon size={14}>
            <Download />
          </ElIcon>
          <span>{fileName}</span>
        </ElLink>
      );
    }
  },
});

export default 'RaFileDownloadRender';
